<?php

namespace App\Http\Controllers\Resources;

use App\Http\Controllers\Controller;
use App\Http\Requests\WxClientRequest;
use App\Models\SimCard;
use App\Models\WxClient;
use App\Plugins\Wechat\Client;
use App\Services\HelpService;
use App\Services\Interfaces\RepoServiceInterface;
use App\Services\WxClientService;
use Auth;
use PHPExcel_Style_Alignment;
use Endroid\QrCode\QrCode;
use Excel;
use PHPExcel_Style_Fill;
use PHPExcel;
use Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WxclientController extends Controller
{
    public $temp_url;
    public $img_url;

    public function __construct(RepoServiceInterface $_repoService)
    {
        $this->_repoService = $_repoService;
        $this->temp_url = config('filesystems.qrcode.temp');
        $this->img_url = config('filesystems.qrcode.img');
        if (!file_exists($this->temp_url)) {
            Helper::makeDir($this->temp_url);
        }
        if (!file_exists($this->img_url)) {
            Helper::makeDir($this->img_url);
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = $this->_repoService->read();
        if (!empty($data))
            return $data;
        else
            return [];
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

        $res = $this->_repoService->find(['_id' => $id]);
        if (is_string($res->_id))
            return $this->_repoService->wxClientInfo($res, $res::WXClIENT_SHOW_FIELDS);
        $res = WxClient::find($id);
        if (!is_null($res))
            return $res;
        else
            return $this->_error('没找到指定的微信号');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(WxClientRequest $request)
    {
        $data = $request->all();
        $temp_url = config('filesystems.qrcode.temp');
        $img_url = config('filesystems.qrcode.img');

        $sim_card = SimCard::find($data['simCardId']);
        if (is_null($sim_card) || empty($sim_card->mobile)) {
            return $this->_error('卡柜不存在或卡柜为空');
        }
        $wx_client = WxClient::where('mobile', $sim_card->mobile)->count();
        if ($wx_client) {
            return $this->_error('该手机号已绑定微信号');
        }
        $data['mobile'] = $sim_card->mobile;
        $data['qrcode'] = $data['qrcode'] ?? '';
        $data['qrImg'] = $data['qrImg'] ?? '';
        if (empty($data['qrcode']) && empty($data['qrImg'])) {
            return $this->_error('二维码字段缺失');
        }
        $res = $this->_repoService->create($data);
        $sim_card->wxClient_id = $res->id;
        $sim_card->save();
        if ($data['qrImg']) {
            //移动并修改上传的图片名称
            if (file_exists($this->temp_url . '/' . $data['qrImg'])) {
                rename($this->temp_url . '/' . $data['qrImg'],
                    $this->img_url . '/' . $res->id . '.png');
            }
        } else {
            $qrCode = new QrCode();
            $qrCode
                ->setText($data['qrcode'])
                ->setSize(200)
                ->setPadding(1)
                ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
                ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
                ->setImageType('png')
                ->render($this->img_url . '/' . $res->id . '.png');
        }
        return $res;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(WxClientRequest $request, $id)
    {
        $data = $request->all();
        $_filter = ['id' => $id];
        if ($request->method() === 'PUT') {
            $sim_card = SimCard::find($data['simCardId']);
            if (is_null($sim_card) || empty($sim_card->mobile)) {
                return $this->_error('卡柜不存在或卡柜为空');
            }
            $wx_client = WxClient::where('mobile', $sim_card->mobile)->first();
            if ($wx_client && $wx_client->id !== $id) {
                return $this->_error('该手机号已绑定微信号');
            }
            $data['mobile'] = $sim_card->mobile;
            $data['qrcode'] = $data['qrcode'] ?? '';
            $data['qrImg'] = $data['qrImg'] ?? '';
            $wxClient = WxClient::find($id);
            if (!empty($data['qrcode']) || !empty($data['qrImg'])) {
                // 编辑:修改了图片,就好删除老图片
                if ($data['qrcode'] != $wxClient->qrcode || !empty($data['qrImg'])) {
                    if (!$data['qrcode']) {
                        //移动并修改上传的图片名称
                        if (file_exists($this->temp_url . '/' . $data['qrImg'])) {
                            rename($this->temp_url . '/' . $data['qrImg'],
                                $this->img_url . '/' . $id . '.png');
                        }
                    } else {
                        $qrCode = new QrCode();
                        $qrCode
                            ->setText($data['qrcode'])
                            ->setSize(200)
                            ->setPadding(1)
                            ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
                            ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
                            ->setImageType('png')
                            ->render($this->img_url . '/' . $id . '.png');
                    }
                }
            }
            $isSave = $this->_repoService->update($_filter, $data);
        } else {
            if (!isset($data['uin'])) {
                return $this->_error('缺失字段：uin');
            }
            $isSave = $this->_repoService->update($_filter,
                ['uin' => $data['uin']]);
        }

        if ($isSave) {
            $wx_client = WxClient::find($id);
            return $this->_repoService->wxClientInfo($wx_client,
                $wx_client::WXCLIENT_LIST_FIELDS);
        } else {
                return $this->_error('修改失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function refresh($id)
    {
        $wx_client = WxClient::where('_id', $id)
            ->first();
        if (is_null($wx_client)) {
            return $this->_error('微信号不存在');
        }
        if (Client::updateInfo($wx_client->uin)) {
            return $this->_repoService
                ->wxClientInfo($wx_client, $wx_client::WXClIENT_OPT_FIELDS);
        } else {
            return $this->_error('更新操作失败');
        }
    }

    /**
     * 清除
     * @param $id
     * @return array
     */
    public function remove($id)
    {
        $wx_client = WxClient::where('_id', $id)
            ->first();
        if (is_null($wx_client)) {
            return $this->_error('微信号不存在');
        }
        if (Client::removeInfo($wx_client->uin)) {
            return $this->_repoService
                ->wxClientInfo($wx_client, $wx_client::WXClIENT_OPT_FIELDS);
        } else {
            return $this->_error('清除操作失败');
        }
    }

    /**
     * 清除Uin
     */

    public function clearUin($wxClientId)
    {
        $WxClientInfo = WxClient::find($wxClientId);
        if (Client::isActive($WxClientInfo->uid)) {
            return $this->_error('该账号在登陆状态');
        }
        if (!empty($WxClientInfo)) {
            $WxClientInfo = $WxClientInfo->toArray();
            if ($WxClientInfo['status'] == 2) {
                DB::table('BannedWxClient')->insertGetId(['info' => $WxClientInfo]);
                $update = WxClient::where('_id', $wxClientId)->update([
                    'uin' => 0,
                    'contacts' => [],
                    'nickName' => '',
                    'password' => '',
                    'status' => 1,
                ]);
                if ($update) {
                    $wx_client = WxClient::find($wxClientId);
                    return $this->_repoService->wxClientInfo($wx_client,
                        $wx_client::WXCLIENT_LIST_FIELDS);
                } else {
                    return $this->_error('清除失败');
                }
            } else {
                return $this->_error('该账号没有被封');
            }
        } else {
            return $this->_error('该ID无数据');
        }
    }

    /**
     * 批量导入微信号
     */

    public function import(Request $request)
    {
        //判断文件是否存在
        if (!$request->hasFile('excel')) {
            return $this->_error('未上传表格');
        }
        $excel = $request->file('excel');
        //拓展名判断
        if ($excel->getClientOriginalExtension() !== 'xlsx') {
            return $this->_error('上传文件格式错误');
        }
        $file_name = Helper::fileName(storage_path('mobile/'), 1, '', 'xlsx');
        if ($excel->isValid()) {
            $excel->move(storage_path('wx'), $file_name);
        } else {
            return $this->_error('上传失败,请稍后再试');
        }
        //数据处理
        return $this->_repoService
            ->importWx(storage_path('wx/' . $file_name), $excel->getClientOriginalName());
    }

    /**
     * 下载空模板
     */

    public function downFileMould()
    {
        $path = storage_path('wx/example/wxmodel.xlsx');
        HelpService::exportModel($path);
    }
}
